package proxy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

/**
 * 自定义 HttpServletRequest
 *
 * @author wxf
 */
public class CustomerHttpServletRequest extends HttpServletRequestWrapper {

    private Map<String, String[]> params = new HashMap<>();
    private String uri;
    private String methodName;

    public CustomerHttpServletRequest(HttpServletRequest request) {
        super(request);
        methodName = request.getMethod();
        //将参数表，赋予给当前的Map以便于持有request中的参数
        //本项目不需要
        // this.params.putAll(request.getParameterMap());
    }


    @Override
    public Enumeration<String> getParameterNames() {
        return new Vector<>(params.keySet()).elements();
    }

    /**
     * 重写getParameter，代表参数从当前类中的map获取
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public String[] getParameterValues(String name) {//同上
        return params.get(name);
    }

    /**
     * 增加多个参数
     */
    public void addAllParameters(Map<Object, ?> otherParams) {
        if (otherParams != null && !otherParams.isEmpty()) {
            for (Map.Entry<Object, ?> entry : otherParams.entrySet()) {
                addParameter(entry.getKey().toString(), entry.getValue());
            }
        }
    }

    /**
     * 增加参数
     */
    public void addParameter(String name, Object value) {
        if (value != null) {
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[]{(String) value});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return params;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    @Override
    public String getRequestURI() {
        return this.uri;
    }

    @Override
    public String getMethod() {
        return this.methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }
}
